package task

import (
    "errors"
    "dhfshop/service/event"
    "dhfshop/models/shopping"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/toolbox"
)

func init(){
	tk1 := toolbox.NewTask("ConfirmOrder", "0 */58 * * * *", func() error {
		if orderslist,_,err := shopping.GetTimeoutSignOrders(-14,"S_ORDER_WAIT_RECEIVE",0,500); err == nil {
		    for _, orders := range orderslist {
			    var result string = ""
				var req = new(event.TradeMsg)
				req.CompanyId = orders.PartnerId
				req.UserId = orders.MemberId
				req.OrderId = orders.OrderId
				req.MsgHeader.EventType = "E_ORDER_RECEIVE"
				//beego.Debug("req.OrderId:", req.OrderId)
				
				message, err := event.EncodeMsg(req)
				if err != nil {
					return err     
				}
				event.KernelBus.Publish("E_ORDER_RECEIVE",message,&result)
				if len(result) > 0 {
					beego.Debug("E_ORDER_RECEIVE:", result)
					err = errors.New(result)
					return err
				}
				
			}
		}
		return nil 	
	})
	//
	tk2 := toolbox.NewTask("CancelOrder", "0 */10 * * * *", func() error {
		if orderslist,_,err := shopping.GetTimeoutCancelOrders(-60*24*3,"S_ORDER_WAIT_PAYMENT",0,500); err == nil {
		    for _, orders := range orderslist {
				ok := shopping.CheckOrderStatusValid(orders.OrderId,"S_ORDER_WAIT_PAYMENT")
				if ok {
				   orders.Status = "S_ORDER_CANCEL"
			       shopping.UpdateOrderStatus(orders)
				}	
			}
		}
		return nil 	
	})
	toolbox.AddTask("ConfirmOrder", tk1)
	toolbox.AddTask("CancelOrder", tk2)
	//toolbox.StartTask()
	defer toolbox.StopTask()
}
